<?php

namespace App\Repository\Sms;

use App\Models\Sms\SmsconfExpressModel as model;
use App\Repository\BaseRepository;
use App\Repository\Orders\OrdersRepository;
use App\Repository\Product\GoodsRepository;
use App\Repository\Product\ProductRepository;
use App\Repository\Shop\SuppilerRepository as supp;

class SmsConfExpressRepository extends BaseRepository
{
    private $model = null;
    private $productModel = null;
    private $goodsModel = null;
    private $smsTmp = null;
    private $orderModel = null;
    private $suppModel = null;

    public function __construct()
    {
        $this->model = new model();
        $this->productModel = new ProductRepository();
        $this->goodsModel = new GoodsRepository();
        $this->smsTmp = new SmsTmpRepository();
        $this->orderModel = new OrdersRepository();
        $this->suppModel = new supp();
        parent::__construct();
    }

    //列表
    public function index($where)
    {
        $cron = $where;
        $cron['order'] = ['orderby' => 'id', 'orderdir' => 'desc'];
        // $cron['where'] = $where;
        // var_dump($cron,111111111);

        $data = $this->search($this->model, $cron, 1, 9000000);
        if (!empty($data['data'])) {
            $data['data'] = usfirstArr($data['data']);
        }
        return $data;
    }

    //添加
    public function add($data)
    {
        //必填 字段
        $mustField = [
            'sms_tmp_id',
            'express_status',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'sms_tmp_id' => '模板不能为空',
            'express_status' => '订单状态不能为空'
        ];
        //       可以多个产品批量新增
        $productIds = $data['product_id'] ?? [];
        if (empty($productIds)) {
            return $this->returnMsg(3, '请选择商品');
        }
        $insertData = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        if (empty($insertData['delay'])) {
            $insertData['delay'] = 0;
        }
        $isTrue = $this->getOne(['sms_tmp_id' => $insertData['sms_tmp_id'], 'express_status' => $insertData['express_status'], 'delay' => $insertData['delay'], 'shop_id' => $data->user->shop_id]);
        if ($isTrue) {
            return $this->returnMsg(3, '该模板已添加');
        }
        $insertData['shop_id'] = (!empty($data->user->shop_id) ? $data->user->shop_id : (!empty($data->user->id) ? $data->user->id : ''));

        //获取模板
        if (!empty($insertData['sms_tmp_id'])) {
            $resSmsTmp = $this->smsTmp->getOne(['id' => $insertData['sms_tmp_id'], 'shop_id' => $insertData['shop_id']], ['id', 'name']);
            if (!$resSmsTmp) {
                return $this->returnMsg(102, '未查询到短信模板');
            }
            $insertData['sms_tmp_name'] = $resSmsTmp->name;
        }
        //商品名称
        if (!empty($insertData['goods_id'])) {
            $goodsArr = $this->goodsModel->getOne(['id' => $insertData['goods_id'], 'shop_id' => $insertData['shop_id']], ['id', 'name', 'goods_code']);
            if (!$goodsArr) {
                return $this->returnMsg(101, '未查询到商品');
            }
            $insertData['goods_name'] = $goodsArr->name;
            $insertData['goods_code'] = $goodsArr->goods_code;
        }
        //订单状态
        if (isset($insertData['express_status'])) {
            $resOrder = $this->orderModel->getOneExpressStatus($insertData['express_status']);
            $insertData['express_status_desc'] = $resOrder;
        }
        //分销商 名称
        if (!empty($insertData['dist_id'])) {
            $resSupp = $this->suppModel->getOne(['shop_id' => $insertData['dist_id'], 'supplier_id' => $insertData['shop_id']], ['id', 'name']);
            if (!$resSupp) {
                return $this->returnMsg(103, '未查询到代理商');
            }
            $insertData['dist_name'] = $resSupp->name;
        }
        if (empty($insertData['dist_id'])) {
            $insertData['dist_id'] = $insertData['shop_id'];
        }
        $insertData['created_at'] = date('Y-m-d H:i:s');
        $insertData['created_by'] = $data->user->id;
        $insertData['created_by_name'] = $data->user->name;

        //        按产品批量新增
        $insertArray = [];
        $products = [];
//        print_r($productIds);
        $rows = $this->productModel->unifiedGetAll([['in', $productIds], ['=', $insertData['shop_id']]], ['id', 'product_code', 'name']);
        foreach ($rows as $k => $v) {
            $products[$v['id']] = $v;
        }
//        echo $this->getLastSql();
//        print_r($products);
        foreach ($productIds as $k => $v) {
            $insertData['product_id'] = $v;
            $insertData['product_name'] = $products[$v]['name'] ?? '';
            $insertData['product_code'] = $products[$v]['product_code'] ?? '';
            $insertArray[] = $insertData;
        }
        $res = $this->model->insert($insertArray);
        if ($res) {
            return $this->returnMsg(200, '添加成功');
        }
        return $this->returnMsg(1, '添加失败');
    }

    //删除
    public function del($params)
    {
        $where = [];
        if (is_array($params['ids'])) {
            if (count($params['ids']) > 1) {
                $where['in']['id'] = $params['ids'];
            } else {
                $where['eq']['id'] = $params['ids'][0];
            }
        } else {
            $where['eq']['id'] = $params['ids'];
        }
        $where['eq']['shop_id'] = $params['user']['shop_id'];
        $this->model->searchWhere($where)->delete();
        return $this->returnMsg(200, '操作完成');
    }

    //修改
    public function edit($where, $data, $isMust = false)
    {
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        if (empty($data['shop_id'])) {
            $data['shop_id'] = $data['user']['shop_id'];
        }
        //过滤字段
        //过滤字段
        $optionalFields = $this->model->getTableField();
        $field = $this->getRealData($data, [], $optionalFields, []);
        //获取模板
        if (!empty($field['sms_tmp_id'])) {
            $resSmsTmp = $this->smsTmp->getOne(['id' => $field['sms_tmp_id'], 'shop_id' => $field['shop_id']], ['id', 'name']);
            if (!$resSmsTmp) {
                return $this->returnMsg(102, '未查询到短信模板');
            }
            $field['sms_tmp_name'] = $resSmsTmp->name;
        }
        //商品名称
        if (!empty($field['goods_id'])) {
            $goodsArr = $this->goodsModel->getOne(['id' => $field['goods_id'], 'shop_id' => $field['shop_id']], ['id', 'name', 'goods_code']);
            if (!$goodsArr) {
                return $this->returnMsg(101, '未查询到商品');
            }
            $field['goods_name'] = $goodsArr->name;
            $field['goods_code'] = $goodsArr->goods_code;
        }
        if (!empty($field['product_id'])) {
            $goodsArr = $this->productModel->getOne(['id' => $field['product_id'], 'shop_id' => $field['shop_id']], ['id', 'name', 'product_code']);
            if (!$goodsArr) {
                return $this->returnMsg(101, '未查询到产品');
            }
            $field['product_name'] = $goodsArr->name;
            $field['product_code'] = $goodsArr->product_code;
        }
        //订单状态
        if (isset($field['order_status'])) {
            $resOrder = $this->orderModel->getOneOrderStatus($field['order_status']);
            $field['order_status_desc'] = $resOrder;
        }
        //分销商 名称
        if (!empty($field['dist_id'])) {
            $resSupp = $this->suppModel->getOne(['shop_id' => $field['dist_id'], 'supplier_id' => $field['shop_id']], ['id', 'name']);
            if (!$resSupp) {
                return $this->returnMsg(103, '未查询到代理商');
            }
            $field['dist_name'] = $resSupp->name;
        }
        if (empty($field['dist_id'])) {
            $field['dist_id'] = $field['shop_id'];
        }
        //先查询是否存在
        $res = $this->model->where($where)->update($field);
        if ($isMust && $res) {
            return $this->returnMsg(200, '修改成功');
        }
        if (!$isMust) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(3, '请重新修改');
    }

    //列表查询
    public function lists($where = [], $page = 1, $limit = 10)
    {
        $res = $this->search($this->model, $where, $page, $limit);

        return $res;
    }

    public function getOne($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }

    public function getAll($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->orderBy('shop_id', 'desc')->get();
    }
}
